package com.stary.code.util;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * jdbc工具类 
 * @author stary
 * @date 2018年7月23日 下午3:45:39
 */
public class JDBCUtils {
	private static final Logger logger=LoggerFactory.getLogger(JDBCUtils.class);
	/**
	 * 获取数据源连接
	 * @param driverClassName
	 * @param url
	 * @param username
	 * @param password
	 * @return
	 * @throws ClassNotFoundException
	 * @throws SQLException
	 */
	public static Connection getConnection(String driverClassName,String url,String username,String password) throws SQLException, ClassNotFoundException{             
		Class.forName(driverClassName);		
		Connection conn = DriverManager.getConnection(url, username, password); 			
		return conn;
	}
	/**
	 * 关闭数据库连接
	 * @param conn
	 */
	public static void closeConnection(Connection conn) {
		if(conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				logger.error("close connection failure", e);
			}
		}
	}
	/**
	 * 获取数据库下的所有表名
	 * @throws SQLException 
	 * @throws ClassNotFoundException
	 */
	public static List<String> getTableNames(String driverClassName,String url,String username,String password) throws ClassNotFoundException, SQLException {
		List<String> tableNames = new ArrayList<>();
		Connection conn = getConnection( driverClassName, url, username, password);
		ResultSet rs = null;
		try {
			//获取数据库的元数据
			DatabaseMetaData db = conn.getMetaData();			
			//从元数据中获取到所有的表名
			rs = db.getTables(null, null, null, new String[] { "TABLE" });

			while(rs.next()) {
				String tableName=rs.getString(3);
				if(driverClassName.contains("oracle")){
					String user=rs.getString(2);
					if(user!=null && user.equals(username.toUpperCase())){
						tableNames.add(tableName);					
					}					
				}else{
					tableNames.add(tableName);
				}
			}
		} catch (SQLException e) {
			logger.error("getTableNames failure", e);
		} finally {
			try {
				rs.close();
				closeConnection(conn);
			} catch (SQLException e) {
				logger.error("close ResultSet failure", e);
			}
		}
		return tableNames;
	}
}
